<template>
  <div class="height100">
    <a-row :gutter="16" class="height100">
      <a-col :span="7">
        <a-card class="tree-container">
          <a-row class="smart-margin-bottom20">
            <a-input v-model:value.trim="keywords" placeholder="请输入" />
          </a-row>
          <a-directory-tree
            v-model:expandedKeys="expandedKeys"
            v-model:selectedKeys="selectedKeys"
            :tree-data="treeData"
            :fieldNames="{ children: 'children', title: 'text', key: 'key' }"
            @select="onTreeSelect"
          >
            <template #title="{ node, text }">
              <span>{{ text }}</span>
            </template>
          </a-directory-tree>
        </a-card>
      </a-col>

      <a-col :span="17" class="height100">
        <!-- class="deviceTob-container" -->
        <a-card>
          <!-- {{ deviceInfo }} -->
          <a-descriptions title="企业信息" :column="3" size="small">
            <!-- <template #extra>
              <a-button type="primary" size="small" @click="onEdit">编辑</a-button>
            </template> -->
            <a-descriptions-item label="名称">{{ deviceInfo.name }}</a-descriptions-item>
            <a-descriptions-item label="创建者">{{ deviceInfo.creator }}</a-descriptions-item>
            <!-- <a-descriptions-item label="uuid">{{ deviceInfo.uuid }}</a-descriptions-item> -->
            <a-descriptions-item label="创建时间">{{ deviceInfo.createdAt }}</a-descriptions-item>
            <a-descriptions-item label="更新时间">{{ deviceInfo.updatedAt }}</a-descriptions-item>
            <!-- <a-descriptions-item label="创建者Uuid">{{ deviceInfo.creatorUuid }}</a-descriptions-item> -->
            <a-descriptions-item label="所属行业">{{ getIndustryName(deviceInfo.industry) }}</a-descriptions-item>
          </a-descriptions>
        </a-card>
        <a-card class="deviceTable-container">
          <a-row class="smart-table-btn-block">
            <div class="smart-table-operate-block">
              <a-button @click.stop="showAddAreaModal">
                <template #icon>
                  <PlusOutlined />
                </template>
                创建区域
              </a-button>
              <a-button @click.stop="showAddDeviceModal" type="primary">
                <template #icon>
                  <PlusOutlined />
                </template>
                创建设备
              </a-button>
              <a-button type="primary" danger @click="batchDelete">
                <template #icon>
                  <DeleteOutlined />
                </template>
                批量删除
              </a-button>
            </div>
          </a-row>

          <div class="deviceTable-box height100">
            <a-table :columns="columns" bordered :data-source="tableData" :pagination="false" rowKey="id">
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'type'">
                  <span :style="{ color: getNodeTypeColor(record.type) }">{{ getNodeTypeName(record.type) }}</span>
                </template>
                <template v-if="column.key === 'deviceType'">
                  <span>{{ getDeviceTypeName(record.deviceType) }} </span>
                </template>
                <template v-if="column.key === 'Status'">
                  <!-- <a-tag :color="getStatusColor(record.Status)">
                    {{ record.Status == 0 ? '离线' : '-' }}
                  </a-tag> -->
                  <span :style="{ color: getStatusColor(record.Status) }"> {{ record.Status == 0 ? '离线' : '-' }}</span>
                </template>

                <!-- 操作列自定义渲染 -->
                <template v-if="column.key === 'action'">
                  <a-button type="link" @click="handleEdit(record)">编辑</a-button>
                  <!-- <a-divider type="vertical" /> -->
                  <a-button v-if="record.type == 1" type="link" @click="handleCopy(record)">拷贝</a-button>
                  <!-- <a-divider v-if="record.type == 1" type="vertical" /> -->
                  <a-button v-if="record.IsEnable == 1 && record.type == 1" type="link" @click="handleStop(record, 0)">停止</a-button>
                  <a-button v-if="record.IsEnable == 0 && record.type == 1" type="link" @click="handleStop(record, 1)">启动</a-button>
                  <!-- <a-divider type="vertical" /> -->
                  <a-popconfirm
                    :title="record.name"
                    ok-text="确认"
                    cancel-text="取消"
                    description="你确定要删除吗?"
                    @confirm="handleDelete(record)"
                    @cancel="cancel"
                  >
                    <a-button type="link" danger>
                      <!-- <DeleteOutlined style="color: red" /> -->
                      删除</a-button
                    >
                  </a-popconfirm>
                </template>
              </template>
            </a-table>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 添加区域弹框 -->
    <a-modal v-model:open="addAreaVisible" :title="areaTitle" @ok="handleAddAreaOk" @cancel="handleAddAreaCancel">
      <a-form :model="areaForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-form-item label="区域名称" required>
          <a-input v-model:value="areaForm.name" />
        </a-form-item>
        <a-form-item label="组态模型">
          <a-select v-model:value="areaForm.displayUid">
            <a-select-option v-for="option in modelOptions" :key="option.ID" :value="option.displayUid">
              {{ option.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="组态展示页面">
          <a-select v-model:value="areaForm.page">
            <a-select-option v-for="option in pageOptions" :key="option.PageId" :value="option.PageId">
              {{ option.PageName }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="区域描述">
          <a-textarea v-model:value="areaForm.description" :auto-size="{ minRows: 3, maxRows: 8 }" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 添加设备弹框 -->
    <a-modal v-model:open="addDeviceVisible" :title="deviceTitle" @ok="handleAddDeviceOk" @cancel="handleAddDeviceCancel">
      <a-form :model="deviceForm" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
        <a-form-item label="设备名称" required>
          <a-input v-model:value="deviceForm.name" />
        </a-form-item>
        <a-form-item label="设备类型" required>
          <a-select v-model:value="deviceForm.deviceType" @change="getSnmpmodellistOptions">
            <a-select-option v-for="(option, key) in deviceTypeOptions" :key="key" :value="option.type">
              {{ option.dec }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="数据模型">
          <a-select v-model:value="deviceForm.deviceType">
            <a-select-option v-for="(option, key) in dataModelOptions" :key="key" :value="option.ID">
              {{ option.name }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="设备标识" required v-show="addDeviceType == 470">
          <a-input v-model:value="deviceForm.DeviceID" />
        </a-form-item>
        <a-form-item label="访问密码" required v-show="addDeviceType == 470">
          <a-input v-model:value="deviceForm.accessPassword" />
        </a-form-item>

        <a-form-item label="Snmp代理地址" required v-show="addDeviceType == 1">
          <a-input v-model:value="deviceForm.SnmpAgentAddress" />
        </a-form-item>
        <a-form-item label="Modbus地址" required v-show="addDeviceType == 2">
          <a-input v-model:value="deviceForm.extra.modbus.address" />
        </a-form-item>
        <a-form-item label="OPCUA连接地址" required v-show="addDeviceType == 3">
          <a-input v-model:value="deviceForm.OPCUAddress" />
        </a-form-item>
        <a-form-item label="IP地址" required v-show="addDeviceType == 15 || addDeviceType == 40">
          <a-input v-model:value="deviceForm.ip" />
        </a-form-item>

        <a-form-item label="插槽号" required v-show="addDeviceType == 15">
          <a-input v-model:value="deviceForm.slotNo" />
        </a-form-item>
        <a-form-item label="机架号" required v-show="addDeviceType == 15">
          <a-input v-model:value="deviceForm.rackNo" />
        </a-form-item>
        <a-form-item label="ClientID" required v-show="addDeviceType == 20">
          <a-input v-model:value="deviceForm.ClientID" />
        </a-form-item>
        <a-form-item label="通信地址" required v-show="addDeviceType == 30">
          <a-input v-model:value="deviceForm.comAddress" />
        </a-form-item>
        <a-form-item label="操作者代码" required v-show="addDeviceType == 30">
          <a-input v-model:value="deviceForm.opCode" />
        </a-form-item>
        <a-form-item label="密码" required v-show="addDeviceType == 30">
          <a-input v-model:value="deviceForm.password" />
        </a-form-item>
        <a-form-item label="前导FE" required v-show="addDeviceType == 30">
          <a-select v-model:value="deviceForm.preambleFE">
            <a-select-option value="0">使能</a-select-option>
            <a-select-option value="1">禁止</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="IEC61850连接地址" required v-show="addDeviceType == 350">
          <a-input v-model:value="deviceForm.IEC61850Addresas" />
        </a-form-item>
        <a-form-item label="端口" required v-show="addDeviceType == 40 || addDeviceType == 350">
          <a-input v-model:value="deviceForm.port" />
        </a-form-item>
        <a-form-item label="公共地址" required v-show="addDeviceType == 40">
          <a-input v-model:value="deviceForm.PublicAddress" />
        </a-form-item>
        <!-- <a-form-item label="设备ID" required>
          deviceForm.extra.modbus.RegisterPack
          <a-input v-model:value="deviceForm.deviceId" placeholder="注册包: FF 00 00 26 40 28 84" />
        </a-form-item>
        <a-form-item label="Modbus地址" required>
          <a-input-number v-model:value="deviceForm.modbusAddress" />
        </a-form-item> -->
        <a-form-item label="经度">
          <a-input v-model:value="deviceForm.longitude" />
        </a-form-item>
        <a-form-item label="纬度">
          <a-input v-model:value="deviceForm.latitude" />
        </a-form-item>
        <a-form-item label="超时时间(毫秒)" required v-show="addDeviceType !== 20">
          <a-input-number style="width: 100%" v-model:value="deviceForm.timeout" :min="0" />
        </a-form-item>
        <a-form-item label="通信失败次数" v-show="addDeviceType !== 20">
          <a-input-number style="width: 100%" v-model:value="deviceForm.failedTimes" :min="0" />
        </a-form-item>
        <a-form-item label="采集时间(毫秒)" v-show="[1, 2, 3, 4, 5, 30, 40.35, 470, 480].includes(Number(addDeviceType))">
          <a-input-number style="width: 100%" v-model:value="deviceForm.interval" :min="0" />
        </a-form-item>
        <a-form-item label="离线是否恢复默认值" required>
          <a-radio-group v-model:value="deviceForm.offlineClear">
            <a-radio :value="1">是</a-radio>
            <a-radio :value="2">否</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="离线默认值" required>
          <a-input v-model:value="deviceForm.offlineDefaultValue" />
        </a-form-item>
        <a-form-item label="设备描述">
          <a-textarea v-model:value="deviceForm.description" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
  
  <script setup>
import { message } from 'ant-design-vue';
import { ref, onMounted, watch, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { cvaiApi } from '/@/api/system/cvai-api';
import _ from 'lodash';

// 表格数据
const tableData = ref([]);

// 表格列配置
const columns = ref([
  { title: '序号', dataIndex: 'id', key: 'id', width: 80 },
  { title: '名称', dataIndex: 'text', key: 'text' },
  { title: '节点类型', dataIndex: 'type', key: 'type' },
  { title: '设备类型', dataIndex: 'deviceType', key: 'deviceType' },
  { title: '状态', dataIndex: 'Status', key: 'Status' },
  { title: '描述', dataIndex: 'description', key: 'description' },
  { title: '操作', key: 'action', width: 200 },
]);

// 添加区域相关
const addAreaVisible = ref(false);
const areaTitle = ref('添加区域');
const areaForm = ref({
  name: '',
  displayUid: '',
  page: '',
  description: '',
});

// 添加设备相关
const addDeviceVisible = ref(false);
const deviceTitle = ref('添加设备');
const deviceForm = ref({
  // name: '',
  // type: 1,
  // deviceId: '',
  // modbusAddress: 0,
  // longitude: 0,
  // latitude: 0,
  // timeout: 1000,
  // interval: 1000,
  // failedTimes: 5,
  // collectTime: 1000,
  // offlineClear: 2,
  // offlineDefaultValue: 0,
  // description: '',
  // extra: '',
  // pid: '',
  // muid: '',
  // deviceType: '',

  type: 1,
  name: '',
  longitude: 0,
  latitude: 0,
  timeout: 1000,
  interval: 1000,
  failedTimes: 5,
  muid: '41c7e3c1-d878-7d69-7a96-8458c0a960c5',
  deviceType: null,
  description: '',
  offlineClear: 2,
  offlineDefaultValue: 0,
  extra: { modbus: { IPAddress: null, Port: null, address: 'Modbus地址', RegisterPack: 1 } },
  IPAddress: '',
  Port: '',
  address: '',
  RegisterPack: '',
  pid: 1799909215,
});

//添加设备对象
const addDeviceObj = ref({
  type: 1,
  name: '',
  longitude: 0,
  latitude: 0,
  timeout: 1000,
  interval: 1000,
  failedTimes: 5,
  muid: '',
  deviceType: null,
  description: '',
  offlineClear: 2,
  offlineDefaultValue: 0,
  extra: { modbus: { IPAddress: null, Port: null, address: 'Modbus地址', RegisterPack: 1 } },
  IPAddress: '',
  Port: '',
  address: '',
  RegisterPack: '',
  pid: 1799909215,
});

//批量删除
const batchDelete = () => {
  // const selectedRows = tableData.value.filter((item) => item.checked);
};

onMounted(() => {
  getTree();
  getSupportDeviceOptions();
  getDeviceInfo();
  getDisplayModelListOptions();
  getSnmpmodellistOptions(1);
});
// -----------------------  筛选 ---------------------
const keywords = ref('');
watch(
  () => keywords.value,
  () => {
    // onSearch();
  }
);

// 树形数据
const treeData = ref([]);
//树节点默认展开
const expandedKeys = ref(['']);
// const expandedKeys = ref(['c633c416-bca1-b5d7-a453-500e11b5acf7']);
const selectedKeys = ref([]);
const selectedTreeObj = ref([]);
function getTree() {
  cvaiApi.getMonitortree().then((res) => {
    treeData.value = res.list;
  });
}
const getStatusColor = (Status) => {
  return Status == 0 ? '#00000087' : 'green';
};

//设备类型options
const deviceTypeOptions = ref([]);
function getSupportDeviceOptions() {
  cvaiApi.getSupportDevice().then((res) => {
    deviceTypeOptions.value = res.list;
  });
}
//数据模型options
const dataModelOptions = ref([]); // 存储数据模型选项
//添加设备的时候 默认type为Modbus设备， addDeviceType 为1
const addDeviceType = ref(1);
function getSnmpmodellistOptions(type) {
  dataModelOptions.value = [];
  addDeviceType.value = type;
  cvaiApi.getSnmpmodellist({ type: type }).then((res) => {
    dataModelOptions.value = res.list; // 将数据模型选项存储到 modelOptions 中
  });
}

//组态模型options
const modelOptions = ref([]);
const pageOptions = ref([]);
function getDisplayModelListOptions() {
  cvaiApi.getDisplayModelList().then((res) => {
    modelOptions.value = res.list;
  });
}

//设备信息的接口信息
const deviceInfo = ref({});
function getDeviceInfo() {
  //TODO
  const obj = {
    uuid: '2773df08-6879-7d88-47f3-4b5bb266a851',
  };
  cvaiApi.getByUuidProjectLists(obj).then((res) => {
    deviceInfo.value = res.data;
  });
}

//根据设备类型id返回设备类型名称
const getDeviceTypeName = (deviceTypeId) => {
  const deviceType = deviceTypeOptions.value.find((item) => item.ID == deviceTypeId);
  return deviceType ? deviceType.dec : '-';
};

//根据节点类型返回节点类型名称
const getNodeTypeName = (nodeType) => {
  return nodeType == 0 ? '区域' : '设备';
};
//根据节点类型返回节点类型名称的颜色
const getNodeTypeColor = (nodeType) => {
  return nodeType == 0 ? '#ffcc00' : '#ff4d4f';
};

const formIndustryOptions = ref([
  { label: '工业互联网', value: 1 },
  { label: '智慧农业', value: 2 },
  { label: '教育', value: 3 },
  { label: '新能源', value: 4 },
  { label: '智能制造', value: 5 },
  { label: '智慧城市', value: 6 },
  { label: '智慧医疗', value: 7 },
  { label: '其他领域', value: 8 },
]);
//所属行业，根据value返回label
const getIndustryName = (value) => {
  const industry = formIndustryOptions.value.find((item) => item.value == value);
  return industry ? industry.label : '-';
};

// 显示添加区域弹框
const showAddAreaModal = () => {
  areaForm.value = {
    name: '',
    displayUid: '',
    page: '',
    description: '',
  };
  if (addAreaObj.value.pid == null) {
    message.error('请选择区域父节点');
    return;
  }
  areaTitle.value = '添加区域';
  addAreaVisible.value = true;
};

// 显示添加设备弹框
const showAddDeviceModal = () => {
  if (addAreaObj.value.pid == null) {
    message.error('请选择区域父节点');
    return;
  }
  // areaForm.value = {
  //   name: '',
  //   displayUid: '',
  //   page: '',
  //   description: '',
  // };
  deviceTitle.value = '添加设备';
  addDeviceVisible.value = true;
};
//添加区域对象
const addAreaObj = ref({
  type: 0,
  name: '',
  description: '',
  configUid: '',
  pid: null,
});

// 添加区域确认
const handleAddAreaOk = () => {
  // console.log('添加区域:', areaForm.value);
  addAreaObj.value.configUid = areaForm.value.displayUid;
  addAreaObj.value.name = areaForm.value.name;
  addAreaObj.value.description = areaForm.value.description;
  if (areaTitle.value == '添加区域') {
    cvaiApi.addMonitor(addAreaObj.value).then((res) => {
      if (res.code == 0) {
        addAreaVisible.value = false;
        message.success('添加成功');
        getTree();
      } else {
        message.error(res.msg);
      }
    });
  } else if (areaTitle.value == '编辑区域') {
    const obj = {
      uuid: areaForm.value.uuid,
      editData: {
        type: areaForm.value.type,
        name: areaForm.value.name,
        description: areaForm.value.description,
        configUid: areaForm.value.displayUid,
        PageUUID: areaForm.value.page,
      },
    };
    cvaiApi.editMonitor(obj).then((res) => {
      if (res.code == 0) {
        addAreaVisible.value = false;
        message.success('编辑成功');
        getTree();
      } else {
        message.error(res.msg);
      }
    });
  }
};

// 添加区域取消
const handleAddAreaCancel = () => {
  addAreaVisible.value = false;
};

// 添加设备确认
const handleAddDeviceOk = () => {
  // console.log(deviceTitle.value, deviceForm.value);
  if (deviceTitle.value == '添加设备') {
    cvaiApi.addMonitor(addDeviceObj.value).then((res) => {
      if (res.code == 0) {
        addDeviceVisible.value = false;
        message.success('添加成功');
        getTree();
      } else {
        message.error(res.msg);
      }
    });
  } else if (deviceTitle.value == '编辑设备') {
    const obj = {
      uuid: addDeviceObj.value.muid,
      editData: {
        type: deviceForm.value.type,
        name: deviceForm.value.name,
        longitude: deviceForm.value.longitude,
        configUid: deviceForm.value.configUid,
        muid: deviceForm.value.muid,
        latitude: deviceForm.value.latitude,
        timeout: deviceForm.value.timeout,
        interval: deviceForm.value.interval,
        failedTimes: deviceForm.value.failedTimes,
        deviceType: deviceForm.value.deviceType,
        description: deviceForm.value.description,
        offlineClear: deviceForm.value.offlineClear,
        offlineDefaultValue: deviceForm.value.offlineDefaultValue,
        extra: JSON.stringify(deviceForm.value.extra),
      },
    };
    cvaiApi.editMonitor(obj).then((res) => {
      if (res.code == 0) {
        addDeviceVisible.value = false;
        message.success('编辑成功');
        getTree();
      } else {
        message.error(res.msg);
      }
    });
  }
};

// 添加设备取消
const handleAddDeviceCancel = () => {
  addDeviceVisible.value = false;
};

//根据当前选择key获取当前节点的信息
const getSelectedNodeInfo = () => {
  const targetKey = selectedKeys.value[0];
  console.log(selectedKeys);

  const findNode = (nodes) => {
    for (const node of nodes) {
      if (node.key === targetKey) {
        return node;
      }
      if (node.children && node.children.length > 0) {
        const found = findNode(node.children);
        if (found) {
          return found;
        }
      }
    }
    return null;
  };
  // 确保视图更新
  nextTick(() => {
    const result = findNode(treeData.value);
    tableData.value = flattenTree(result);
  });

  // return findNode(treeData.value);
};
// 添加深度监听
watch(
  tableData,
  (newValue, oldValue) => {
    nextTick(() => {
      tableData.value = newValue;
    });
    console.log('tableData 数据已更新:', newValue);
    // 这里可以添加数据更新后需要执行的逻辑
    // 例如重新渲染表格、更新其他关联数据等
  },
  { deep: true }
);

// 树节点选择
const onTreeSelect = (selectedKeys, info) => {
  // console.log('selected', selectedKeys);
  selectedKeys.value = selectedKeys;

  selectedTreeObj.value = info.selectedNodes[0];
  console.log(selectedTreeObj.value);

  tableData.value = [];
  tableData.value = flattenTree(selectedTreeObj.value);

  addAreaObj.value.pid = selectedTreeObj.value.value.sid;
  // console.log(selectedTreeObj.value.value.sid);
};

/**
 * 扁平化嵌套对象
 * @param {Object} obj - 待扁平化的对象
 * @returns {Object} 扁平化后的对象
 */
function flattenObject(obj) {
  let result = {};
  for (const key in obj) {
    if (typeof obj[key] === 'object' && obj[key] !== null && !Array.isArray(obj[key])) {
      const flattened = flattenObject(obj[key]);
      for (const subKey in flattened) {
        result[subKey] = flattened[subKey];
      }
    } else {
      result[key] = obj[key];
    }
  }
  return result;
}

function flattenTree(tree) {
  let result = [];

  // 处理输入可能是单个节点或节点数组的情况
  const nodes = Array.isArray(tree) ? tree : [tree];

  nodes.forEach((node) => {
    // 复制当前节点，避免修改原数据
    let flatNode = { ...node };
    // 移除 children 属性
    delete flatNode.children;
    // 扁平化节点对象
    flatNode = flattenObject(flatNode);
    result.push(flatNode);

    // 递归处理子节点
    if (node.children && node.children.length) {
      result = result.concat(flattenTree(node.children));
    }
  });

  return result;
}

// 编辑操作
const handleEdit = (record) => {
  console.log('编辑:', record);
  getSnmpmodellistOptions(record.deviceType);

  // type0是编辑区域，type1是编辑设备
  if (record.type == 0) {
    cvaiApi.getMonitorDetail({ muid: record.configUid }).then((res) => {
      if (res.code == 0) {
        pageOptions.value = res.layer;
      }
    });
    areaTitle.value = '编辑区域';
    addAreaVisible.value = true;
    areaForm.value.name = record.name;
    areaForm.value.displayUid = record.configUid;
    areaForm.value.description = record.description;
    areaForm.value.uuid = record.key;
    areaForm.value.type = record.type;
    areaForm.value.page = record.PageUUID;
  } else {
    //TODO
    deviceTitle.value = '编辑设备';
    addDeviceVisible.value = true;
    record.extra = JSON.parse(record.extra);
    deviceForm.value = record;
    addDeviceObj.value.muid = record.key;
    // console.log(addDeviceObj.value);
  }
};

// 拷贝操作
const handleCopy = (record) => {
  console.log('拷贝:', record);
};

// 停止操作
const handleStop = (record, IsEnable) => {
  // console.log('停止:', record);
  const obj = {
    uuid: record.key,
    editData: {
      IsEnable: IsEnable,
      name: record.name,
      deviceType: record.deviceType,
    },
  };
  cvaiApi.setDeviceStartOrStop(obj).then(async (res) => {
    if (res.code == 0) {
      getTree();
      getSelectedNodeInfo();
      message.success('操作成功');
    } else {
      message.error('操作失败');
    }
  });
};

// 取消操作
const cancel = (e) => {
  console.log(e);
  // message.info('点击了取消');
};

// 递归查找指定 key 的节点是否有 children
const hasChildrenByKey = (nodes, targetKey) => {
  for (const node of nodes) {
    if (node.key === targetKey) {
      return node.children && node.children.length > 0;
    }
    if (node.children) {
      const result = hasChildrenByKey(node.children, targetKey);
      if (result) return true;
    }
  }
  return false;
};

// 删除操作
const handleDelete = (record) => {
  // console.log('删除:', record.key);

  const hasChildren = hasChildrenByKey(treeData.value, record.key);
  if (hasChildren) {
    message.warning('当前区域存在节点，请先删除此区域下面的所有节点.');
    return;
  }

  cvaiApi.delMonitor({ uuid: record.key }).then((res) => {
    if (res.code == 0) {
      getTree();
      message.success('删除成功');
      tableData.value = [];
    } else {
      message.error('删除失败');
    }
  });
};
</script>

<style scoped lang="less">
.height100 {
  height: 100%;
}
.deviceTable-box {
  display: flex;
  flex-direction: column;

  .deviceTable {
    flex-grow: 2;
  }
}
.tree-container {
  height: 100%;
  .tree {
    height: 618px;
    margin-top: 10px;
    overflow-x: hidden;
  }

  .sort-flag-row {
    margin-top: 10px;
    margin-bottom: 10px;
  }

  .sort-span {
    margin-left: 5px;
  }
  .no-data {
    margin: 10px;
  }
}
.deviceTable-container {
  height: 80%;
  margin-top: 12px;
  overflow-y: scroll;
}
.deviceTob-container {
  height: 23%;
  margin-bottom: 14px;
}
</style>